package com.chijun.mf;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.chijun.mform.FormBuilder;
import com.chijun.mform.create.ICreateFormListener;
import com.chijun.mform.create.IServerSaveOverResult;
import com.chijun.mform.create.IWaitResult;
import com.chijun.mform.create.dialog.IGetServerPersonResult;
import com.chijun.mform.create.field.Field;
import com.chijun.mform.create.mode.Form;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormSaveData;
import com.chijun.mform.full.IGetFieldAllFormListener;
import com.chijun.mform.full.IHandleWriterData;
import com.chijun.mform.full.IResultFormConfig;
import com.chijun.mform.full.mode.ModeFormFullApprovePerson;
import com.chijun.mform.full.mode.ModeServerSubmitData;
import com.chijun.mform.process.IHandlerLoadFormFull;
import com.chijun.mform.process.IWaitLoadCompleteResultDataListener;
import com.chijun.mform.process.IWaitUploadCompleteListener;
import com.chijun.mform.show.ShowFullDataActivity;
import com.example.ccj.b.a.BaseActivity;
import com.example.ccj.b.c.custom.tree.TreeMode;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.u.DeviceUtils;
import com.example.ccj.u.JsonUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.PhoneUtils;
import com.example.ccj.u.SPUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.server.HeaderInterceptor;
import com.example.ccj.u.server.MyObserver;
import com.example.ccj.u.server.RequestDataHolder;
import com.example.ccj.u.server.Result;
import com.example.ccj.u.tengxun.cos.COS;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    @Override
    public void initData(@Nullable Bundle bundle) {

    }

    @Override
    public void initView(@Nullable Bundle bundle, @Nullable View view) {
        //获取SH1
        LogUtils.d(DeviceUtils.sHA1(this));

        //服务器配置
        RequestDataHolder.ADDRESS = "10.0.2.2"; //虚拟机地址
//        RequestDataHolder.ADDRESS = "clcaxh.a1.luyouxia.net:22066"; //虚拟机地址
//        RequestDataHolder.ADDRESS = "192.168.110.100"; //真机地址  根据网络环境修改

        RequestDataHolder.PORT = "8085";//端口



        //服务器请求头配置
        //设备唯一码
        String imei = DeviceUtils.getUniqueDeviceId();
        HeaderInterceptor.header.put("imei", imei);

        //服务器请求头配置
        HeaderInterceptor.header.put("autograph", md5(imei, "chijun"));
        HeaderInterceptor.header.put("token", "49e63ca9d37e24da7e72288e37340209_1706621176856");
        HeaderInterceptor.header.put("Device_type", DeviceUtils.getManufacturer() + "-" + DeviceUtils.getModel());
        HeaderInterceptor.header.put("DeviceId", DeviceUtils.getUniqueDeviceId());
        HeaderInterceptor.header.put("PhoneType", String.valueOf(PhoneUtils.getPhoneType()));
        HeaderInterceptor.header.put("MacAddress", DeviceUtils.getMacAddress());
        HeaderInterceptor.header.put("user_id", "519957681745758");


        //必备参数配置
        SPUtils.getInstance().put("user_id","519957681745758");
        SPUtils.getInstance().put("user_name","曹驰珺");
        //获取cos秘钥
        COS.getInstance().getSts();
        //表单文件存储配置
        FormBuilder.BUCKET_NAME = "chijun-1320231608";
        FormBuilder.DI_YU = "ap-beijing";
        //用户组织名称
        FormBuilder.organization_name = "山东省驰珺网络科技有限公司";
        FormBuilder.CannotSetPermissionsFieldTypeArray = new ArrayList<>();
        FormBuilder.CannotSetPermissionsFieldTypeArray.add(FormField.JI_SUAN_GONG_SHI);
        FormBuilder.CannotSetPermissionsFieldTypeArray.add(FormField.GUAN_LIAN_BIAO_DAN);


        writeDataFormId = "616422801997565952";
        fullDataId = "20250102152553905";

//        FormBuilder.getInstance().getCreateFormListener() = new ICreateFormListener() {
//            @Override
//            public void getCreateFormConfig(IWaitResult iWaitResult) {
//
//            }
//
//            @Override
//            public void save(Context context, FormSaveData formSaveData, IServerSaveOverResult serverSaveOverResult) {
//                saveFormData(context,formSaveData,serverSaveOverResult);
//            }
//
//            @Override
//            public List<TreeMode> resultTreeModeList(IGetServerPersonResult iGetServerPersonResult) {
//                getPerson(iGetServerPersonResult);
//                return null;
//            }
//        };

        //新建表单
        Button mBtn =  findViewById(R.id.main_test);
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                openCreateForm();
                openCreateFormView();
            }
        });

        //填写表单
        Button writeForm = findViewById(R.id.main_test_write_form);
        writeForm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFormFullData();
            }
        });

        //加载填写的数据
        Button fulllDataB = findViewById(R.id.main_test_load_full_data);
        fulllDataB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDddd();
            }
        });

        Button formList = findViewById(R.id.main_test_list);
        formList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ShowFullDataActivity.class);
                startActivity(intent);
            }
        });
    }

    String writeDataFormId = "616422801997565952";//测试填写的表单id
    String fullDataId = "20241231022016992";//测试加载数据的表单id



    private void getDddd(){
        FormBuilder.getInstance().showLoadFormFullActivityToFormFullId(this, fullDataId);
    }


    @Override
    public int initContentView() {
        return R.layout.activity_main;
    }


    /**
     * 获取表单配置数据用以填写表单
     */
    private void getFormFullData(){
        // TODO: 2024/12/20 测试环境使用测试数据
        FormBuilder.getInstance().showLoadFormActivityToFormId(this, writeDataFormId);
    }


//    , new IHandleWriterData() {
//        @Override
//        public void getAllForm(IGetFieldAllFormListener getFieldAllFormListener) {
//            CreateFormServiceImpl.getInstance().getAllForm("")
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new MyObserver<Result>() {
//                        @Override
//                        public void onNext(Result result) {
//                            List<Form> listBean = JsonUtils.toListBean(result.getData(), Form.class);
//                            getFieldAllFormListener.onResult(listBean);
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            super.onError(e);
//                            getFieldAllFormListener.onError(e.getMessage());
//                        }
//                    });
//        }
//
//        @Override
//        public void uploadServer(ModeServerSubmitData saveFormData, IWaitResult iWaitResult) {
//            Map<String,String> submitMap = new HashMap<>();
//            submitMap.put("form_data",JSON.toJSONString(saveFormData.launchedForm));
//            submitMap.put("form_file_data",JSON.toJSONString(saveFormData.formFullFileData));
//            submitMap.put("form_approve_person",JSON.toJSONString(saveFormData.formFullApprovePerson));
//            submitMap.put("form_or_field_data",JSON.toJSONString(saveFormData.formOrdinaryFieldData));
//
//            CreateFormServiceImpl.getInstance().saveFormData(JSON.toJSONString(submitMap))
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new MyObserver<Result>() {
//                        @Override
//                        public void onNext(Result result) {
//                            iWaitResult.onResult(result.getData());
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            iWaitResult.onError(e.getMessage());
//                            super.onError(e);
//                        }
//                    });
//        }
//
//        @Override
//        public void getFormFullConfig(String formId, IResultFormConfig iResultFormConfig) {
//            CreateFormServiceImpl.getInstance().getFillInFormData(formId)
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new MyObserver<Result>() {
//                        @Override
//                        public void onNext(Result result) {
//                            iResultFormConfig.result(result.getData());
//                        }
//                        @Override
//                        public void onError(Throwable e) {
//                            super.onError(e);
//                            iResultFormConfig.onError(e.getMessage());
//                        }
//                    });
//        }
//    }


    //创建表单
    private void openCreateFormView(){
        FormBuilder.getInstance().showCreateFormActivity(MainActivity.this);
    }


    /**
     * 上传表单数据到服务器
     * @param context1 上下文
     * @param formSaveData 表单数据
     */
    private void saveFormData(Context context1, FormSaveData formSaveData,IServerSaveOverResult serverSaveOverResult){
        LoadingDialog loadingDialog = new LoadingDialog(context1);
        loadingDialog.showLoading();

        //汇总数据
        Map<String,String> saveData = new HashMap<>();
        if (formSaveData.form != null) saveData.put("form", JSON.toJSONString(formSaveData.form));
        if (formSaveData.formFieldList != null) saveData.put("form_field", JSON.toJSONString(formSaveData.formFieldList));
        if (formSaveData.formFieldOptionList != null && !formSaveData.formFieldOptionList.isEmpty()) saveData.put("form_field_option", JSON.toJSONString(formSaveData.formFieldOptionList));
        if (formSaveData.formOptionReFieldList != null && !formSaveData.formOptionReFieldList.isEmpty()) saveData.put("form_field_option_re", JSON.toJSONString(formSaveData.formOptionReFieldList));
        if (formSaveData.formApproveProcessList != null && !formSaveData.formApproveProcessList.isEmpty()) saveData.put("form_approve_process", JSON.toJSONString(formSaveData.formApproveProcessList));
        if (formSaveData.formApprovePersonList != null && !formSaveData.formApprovePersonList.isEmpty()) saveData.put("form_approve_person", JSON.toJSONString(formSaveData.formApprovePersonList));
        if (formSaveData.formProcessToFieldPermissionList != null && !formSaveData.formProcessToFieldPermissionList.isEmpty()) saveData.put("form_approve_process_permission", JSON.toJSONString(formSaveData.formProcessToFieldPermissionList));
        if (formSaveData.formFilledList != null && !formSaveData.formFilledList.isEmpty()) saveData.put("form_filled", JSON.toJSONString(formSaveData.formFilledList));
        if (formSaveData.formUserList != null && !formSaveData.formUserList.isEmpty()) saveData.put("form_user", JSON.toJSONString(formSaveData.formUserList));
        if (formSaveData.formAdminList != null && !formSaveData.formAdminList.isEmpty()) saveData.put("form_admin", JSON.toJSONString(formSaveData.formAdminList));


        //上传服务器
        CreateFormServiceImpl.getInstance()
                .saveCreateForm(JSON.toJSONString(saveData))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Result>() {
                    @Override
                    public void onNext(Result result) {
                        if (result.isSuccess()) {
                            //清空本地数据库缓存数据
                            FormBuilder.clearTableData(context1);
                            ToastUtils.showShort("保存完毕");
                            serverSaveOverResult.result(result.isSuccess());
                        } else {
                            ToastUtils.showShort("保存失败：" + result.getMessage());
                        }

                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        loadingDialog.dismiss();
                        LogUtils.e(e);
                        ToastUtils.showShort("保存失败：" + e.getMessage());
                    }
                });
    }


    private void getPerson(IGetServerPersonResult iGetServerPersonResult){
        CreateFormServiceImpl.getInstance().getCreateProcessPerson().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Result>() {
                    @Override
                    public void onNext(Result result) {
                        if (!StringUtils.isEmpty(result.getData())) {
                            List<TreeMode> treeModeList = JsonUtils.toListBean(result.getData(), TreeMode.class);
                            LogUtils.d("解析后的人员配置：" + treeModeList.size());
                            if (treeModeList.isEmpty()) {
                                ToastUtils.showShort("人员列表解析失败：" + result.getData());
                            } else {
                                iGetServerPersonResult.result(treeModeList);
                                FormBuilder.getInstance().setTreeModeList(treeModeList);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtils.showShort("获取人员列表失败：" + e.getMessage());
                    }
                });

    }

    // 带秘钥加密
    public static String md5(String text, String key) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            String str = text+key;
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            return  new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}